package club.gskj.gulimall.order.listener;

import club.gskj.gulimall.order.config.AlipayTemplate;
import club.gskj.gulimall.order.service.OrderService;
import club.gskj.gulimall.order.vo.PayAsyncVo;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/***
 *  监听 支付宝异步响应处理
 */
@Controller
public class PrderPayedListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    /***
     *  接受支付宝异步发送的订单支付请求信息
     */
    @PostMapping("/payed/notify")
    @ResponseBody
    public String payedNotify(PayAsyncVo payAsyncVo, HttpServletRequest request) throws Exception {
        // 获取请求携带的所有数据
//        Map<String, String[]> parameterMap = request.getParameterMap();
//        for (String key : parameterMap.keySet()) {
//            String parameter = request.getParameter(key);
//            System.out.println("参数名: " + key + " 参数值: " + parameter);
//        }
//        System.out.println("支付宝异步通知: " + JSON.toJSONString(parameterMap));
        // 只要收到支付宝响应发异步通知，就返回支付宝succees。支付宝就不会重复发送此通知

        // TODO 核心验签
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

        // 验证签名是否为支付宝请求
        if (signVerified) {
            System.out.println("支付宝签名验证成功！");
            // 处理异步结果，设置订单状态
            // 处理成功 返回succee, 处理失败返回不是success即可。(即可通知支付宝继续发送异步请求)
            String result = orderService.handlePayResult(payAsyncVo);
            return result;
        }
        System.out.println("支付宝签名验证失败！");
        return "error";
    }
}
